@file:Suppress("unused")

package com.sscl.baselibrary.widget

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.util.AttributeSet
import android.view.KeyEvent
import android.view.MotionEvent
import android.view.View.OnClickListener
import android.widget.CheckBox
import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.TextView
import com.sscl.baselibrary.R
import com.sscl.baselibrary.utils.BaseManager
import com.sscl.baselibrary.utils.BaseManager.newScheduledExecutorService
import com.sscl.baselibrary.utils.DebugUtil
import java.util.Locale
import java.util.concurrent.ScheduledExecutorService
import java.util.concurrent.TimeUnit

/**
 * 字母与数字的组合键盘
 *
 * @author jackie
 */
class LetterInputMethodView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {
    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     *
     * 私有成员变量
     *
     * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
    /**
     * 自动删除文本的定时器
     */
    private var autoDeleteTimer: ScheduledExecutorService? = null

    /**
     * 显示键盘的容器
     */
    private lateinit var keyboardContent: LinearLayout

    /**
     * 数字键 1，2，3，4，5，6，7，8，9，0
     */
    private lateinit var numberTv1: TextView
    private lateinit var numberTv2: TextView
    private lateinit var numberTv3: TextView
    private lateinit var numberTv4: TextView
    private lateinit var numberTv5: TextView
    private lateinit var numberTv6: TextView
    private lateinit var numberTv7: TextView
    private lateinit var numberTv8: TextView
    private lateinit var numberTv9: TextView
    private lateinit var numberTv0: TextView

    /**
     * 字母 Q,W,E,R,T,Y,U,I,O,P
     */
    private lateinit var letterTvQ: TextView
    private lateinit var letterTvW: TextView
    private lateinit var letterTvE: TextView
    private lateinit var letterTvR: TextView
    private lateinit var letterTvT: TextView
    private lateinit var letterTvY: TextView
    private lateinit var letterTvU: TextView
    private lateinit var letterTvI: TextView
    private lateinit var letterTvO: TextView
    private lateinit var letterTvP: TextView

    /**
     * 字母 A,S,D,F,G,H,J,K,L
     */
    private lateinit var letterTvA: TextView
    private lateinit var letterTvS: TextView
    private lateinit var letterTvD: TextView
    private lateinit var letterTvF: TextView
    private lateinit var letterTvG: TextView
    private lateinit var letterTvH: TextView
    private lateinit var letterTvJ: TextView
    private lateinit var letterTvK: TextView
    private lateinit var letterTvL: TextView

    /**
     * 字母 Z,X,C,V,B,N,M
     */
    private lateinit var letterTvZ: TextView
    private lateinit var letterTvX: TextView
    private lateinit var letterTvC: TextView
    private lateinit var letterTvV: TextView
    private lateinit var letterTvB: TextView
    private lateinit var letterTvN: TextView
    private lateinit var letterTvM: TextView

    /**
     * 清空
     */
    private lateinit var capslockCb: CheckBox

    /**
     * 删除
     */
    private lateinit var deleteTv: RelativeLayout

    /**
     * 显示键盘的按钮
     */
    private lateinit var showKeyboardCb: CheckBox

    /**
     * 显示键盘状态的文本
     */
    private lateinit var showKeyboardHintTv: TextView

    /**
     * 显示键盘的按钮的容器
     */
    private lateinit var showKeyboardContent: RelativeLayout

    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     *
     * 私有成员常量
     *
     * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
    private val onClickListener = OnClickListener { v ->
        when (v) {
            numberTv1 -> {
                pressKey(KeyEvent.KEYCODE_1)
            }

            numberTv2 -> {
                pressKey(KeyEvent.KEYCODE_2)
            }

            numberTv3 -> {
                pressKey(KeyEvent.KEYCODE_3)
            }

            numberTv4 -> {
                pressKey(KeyEvent.KEYCODE_4)
            }

            numberTv5 -> {
                pressKey(KeyEvent.KEYCODE_5)
            }

            numberTv6 -> {
                pressKey(KeyEvent.KEYCODE_6)
            }

            numberTv7 -> {
                pressKey(KeyEvent.KEYCODE_7)
            }

            numberTv8 -> {
                pressKey(KeyEvent.KEYCODE_8)
            }

            numberTv9 -> {
                pressKey(KeyEvent.KEYCODE_9)
            }

            numberTv0 -> {
                pressKey(KeyEvent.KEYCODE_0)
            }

            letterTvQ -> {
                pressLetterKey(KeyEvent.KEYCODE_Q)
            }

            letterTvW -> {
                pressLetterKey(KeyEvent.KEYCODE_W)
            }

            letterTvE -> {
                pressLetterKey(KeyEvent.KEYCODE_E)
            }

            letterTvR -> {
                pressLetterKey(KeyEvent.KEYCODE_R)
            }

            letterTvT -> {
                pressLetterKey(KeyEvent.KEYCODE_T)
            }

            letterTvY -> {
                pressLetterKey(KeyEvent.KEYCODE_Y)
            }

            letterTvU -> {
                pressLetterKey(KeyEvent.KEYCODE_U)
            }

            letterTvI -> {
                pressLetterKey(KeyEvent.KEYCODE_I)
            }

            letterTvO -> {
                pressLetterKey(KeyEvent.KEYCODE_O)
            }

            letterTvP -> {
                pressLetterKey(KeyEvent.KEYCODE_P)
            }

            letterTvA -> {
                pressLetterKey(KeyEvent.KEYCODE_A)
            }

            letterTvS -> {
                pressLetterKey(KeyEvent.KEYCODE_S)
            }

            letterTvD -> {
                pressLetterKey(KeyEvent.KEYCODE_D)
            }

            letterTvF -> {
                pressLetterKey(KeyEvent.KEYCODE_F)
            }

            letterTvG -> {
                pressLetterKey(KeyEvent.KEYCODE_G)
            }

            letterTvH -> {
                pressLetterKey(KeyEvent.KEYCODE_H)
            }

            letterTvJ -> {
                pressLetterKey(KeyEvent.KEYCODE_J)
            }

            letterTvK -> {
                pressLetterKey(KeyEvent.KEYCODE_K)
            }

            letterTvL -> {
                pressLetterKey(KeyEvent.KEYCODE_L)
            }

            letterTvZ -> {
                pressLetterKey(KeyEvent.KEYCODE_Z)
            }

            letterTvX -> {
                pressLetterKey(KeyEvent.KEYCODE_X)
            }

            letterTvC -> {
                pressLetterKey(KeyEvent.KEYCODE_C)
            }

            letterTvV -> {
                pressLetterKey(KeyEvent.KEYCODE_V)
            }

            letterTvB -> {
                pressLetterKey(KeyEvent.KEYCODE_B)
            }

            letterTvN -> {
                pressLetterKey(KeyEvent.KEYCODE_N)
            }

            letterTvM -> {
                pressLetterKey(KeyEvent.KEYCODE_M)
            }

            deleteTv -> {
                pressKey(KeyEvent.KEYCODE_DEL)
            }

            showKeyboardContent -> {
                showKeyboardCb.isChecked = !showKeyboardCb.isChecked
            }
        }
    }

    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     *
     * 构造方法
     *
     * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
    init {
        inflate(context, R.layout.com_jackiepenghe_baselibrary_layout_letter_input_method, this)
        initViews()
        initEvents()
    }
    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     *
     * 公开方法
     *
     * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

    fun showHideKeyboardBtn(visible: Boolean) {
        if (visible) {
            showKeyboardContent.visibility = VISIBLE
        } else {
            showKeyboardContent.visibility = GONE
        }
    }
    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     *
     * 私有方法
     *
     * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
    /**
     * 初始化视图控件
     */
    private fun initViews() {
        numberTv1 = findViewById(R.id.number_tv_1)
        numberTv2 = findViewById(R.id.number_tv_2)
        numberTv3 = findViewById(R.id.number_tv_3)
        numberTv4 = findViewById(R.id.number_tv_4)
        numberTv5 = findViewById(R.id.number_tv_5)
        numberTv6 = findViewById(R.id.number_tv_6)
        numberTv7 = findViewById(R.id.number_tv_7)
        numberTv8 = findViewById(R.id.number_tv_8)
        numberTv9 = findViewById(R.id.number_tv_9)
        numberTv0 = findViewById(R.id.number_tv_0)
        letterTvQ = findViewById(R.id.letter_tv_q)
        letterTvW = findViewById(R.id.letter_tv_w)
        letterTvE = findViewById(R.id.letter_tv_e)
        letterTvR = findViewById(R.id.letter_tv_r)
        letterTvT = findViewById(R.id.letter_tv_t)
        letterTvY = findViewById(R.id.letter_tv_y)
        letterTvU = findViewById(R.id.letter_tv_u)
        letterTvI = findViewById(R.id.letter_tv_i)
        letterTvO = findViewById(R.id.letter_tv_o)
        letterTvP = findViewById(R.id.letter_tv_p)
        letterTvA = findViewById(R.id.letter_tv_a)
        letterTvS = findViewById(R.id.letter_tv_s)
        letterTvD = findViewById(R.id.letter_tv_d)
        letterTvF = findViewById(R.id.letter_tv_f)
        letterTvG = findViewById(R.id.letter_tv_g)
        letterTvH = findViewById(R.id.letter_tv_h)
        letterTvJ = findViewById(R.id.letter_tv_j)
        letterTvK = findViewById(R.id.letter_tv_k)
        letterTvL = findViewById(R.id.letter_tv_l)
        letterTvZ = findViewById(R.id.letter_tv_z)
        letterTvX = findViewById(R.id.letter_tv_x)
        letterTvC = findViewById(R.id.letter_tv_c)
        letterTvV = findViewById(R.id.letter_tv_v)
        letterTvB = findViewById(R.id.letter_tv_b)
        letterTvN = findViewById(R.id.letter_tv_n)
        letterTvM = findViewById(R.id.letter_tv_m)
        deleteTv = findViewById(R.id.letter_tv_delete)
        capslockCb = findViewById(R.id.letter_tv_capslock)
        showKeyboardCb = findViewById(R.id.show_keyboard_btn)
        showKeyboardHintTv = findViewById(R.id.show_keyboard_hint_tv)
        keyboardContent = findViewById(R.id.key_board_content)
        showKeyboardContent = findViewById(R.id.show_keyboard_content)
    }

    /**
     * 初始化事件
     */
    @SuppressLint("ClickableViewAccessibility")
    private fun initEvents() {
        numberTv1.setOnClickListener(onClickListener)
        numberTv2.setOnClickListener(onClickListener)
        numberTv3.setOnClickListener(onClickListener)
        numberTv4.setOnClickListener(onClickListener)
        numberTv5.setOnClickListener(onClickListener)
        numberTv6.setOnClickListener(onClickListener)
        numberTv7.setOnClickListener(onClickListener)
        numberTv8.setOnClickListener(onClickListener)
        numberTv9.setOnClickListener(onClickListener)
        numberTv0.setOnClickListener(onClickListener)
        letterTvQ.setOnClickListener(onClickListener)
        letterTvW.setOnClickListener(onClickListener)
        letterTvE.setOnClickListener(onClickListener)
        letterTvR.setOnClickListener(onClickListener)
        letterTvT.setOnClickListener(onClickListener)
        letterTvY.setOnClickListener(onClickListener)
        letterTvU.setOnClickListener(onClickListener)
        letterTvI.setOnClickListener(onClickListener)
        letterTvO.setOnClickListener(onClickListener)
        letterTvP.setOnClickListener(onClickListener)
        letterTvA.setOnClickListener(onClickListener)
        letterTvS.setOnClickListener(onClickListener)
        letterTvD.setOnClickListener(onClickListener)
        letterTvF.setOnClickListener(onClickListener)
        letterTvG.setOnClickListener(onClickListener)
        letterTvH.setOnClickListener(onClickListener)
        letterTvJ.setOnClickListener(onClickListener)
        letterTvK.setOnClickListener(onClickListener)
        letterTvL.setOnClickListener(onClickListener)
        letterTvZ.setOnClickListener(onClickListener)
        letterTvX.setOnClickListener(onClickListener)
        letterTvC.setOnClickListener(onClickListener)
        letterTvV.setOnClickListener(onClickListener)
        letterTvB.setOnClickListener(onClickListener)
        letterTvN.setOnClickListener(onClickListener)
        letterTvM.setOnClickListener(onClickListener)
        deleteTv.setOnClickListener(onClickListener)
        showKeyboardContent.setOnClickListener(onClickListener)
        deleteTv.setOnLongClickListener {
            DebugUtil.warnOut(TAG, "deleteTv onLongClick")
            startAutoDeleteTimer()
            true
        }
        deleteTv.setOnTouchListener { _, event ->
            if (event.action == MotionEvent.ACTION_UP) {
                stopAutoDeleteTimer()
            }
            false
        }
        capslockCb.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) {
                showUpperText()
            } else {
                showLowerText()
            }
        }
        showKeyboardCb.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) {
                keyboardContent.visibility = GONE
                showKeyboardHintTv.text = "弹出键盘"
            } else {
                keyboardContent.visibility = VISIBLE
                showKeyboardHintTv.text = "隐藏键盘"
            }
        }
    }

    /**
     * 显示大写文本
     */
    private fun showUpperText() {
        letterTvQ.text = letterTvQ.text.toString().uppercase(Locale.getDefault())
        letterTvW.text = letterTvW.text.toString().uppercase(Locale.getDefault())
        letterTvE.text = letterTvE.text.toString().uppercase(Locale.getDefault())
        letterTvR.text = letterTvR.text.toString().uppercase(Locale.getDefault())
        letterTvT.text = letterTvT.text.toString().uppercase(Locale.getDefault())
        letterTvY.text = letterTvY.text.toString().uppercase(Locale.getDefault())
        letterTvU.text = letterTvU.text.toString().uppercase(Locale.getDefault())
        letterTvI.text = letterTvI.text.toString().uppercase(Locale.getDefault())
        letterTvO.text = letterTvO.text.toString().uppercase(Locale.getDefault())
        letterTvP.text = letterTvP.text.toString().uppercase(Locale.getDefault())
        letterTvA.text = letterTvA.text.toString().uppercase(Locale.getDefault())
        letterTvS.text = letterTvS.text.toString().uppercase(Locale.getDefault())
        letterTvD.text = letterTvD.text.toString().uppercase(Locale.getDefault())
        letterTvF.text = letterTvF.text.toString().uppercase(Locale.getDefault())
        letterTvG.text = letterTvG.text.toString().uppercase(Locale.getDefault())
        letterTvH.text = letterTvH.text.toString().uppercase(Locale.getDefault())
        letterTvJ.text = letterTvJ.text.toString().uppercase(Locale.getDefault())
        letterTvK.text = letterTvK.text.toString().uppercase(Locale.getDefault())
        letterTvL.text = letterTvL.text.toString().uppercase(Locale.getDefault())
        letterTvZ.text = letterTvZ.text.toString().uppercase(Locale.getDefault())
        letterTvX.text = letterTvX.text.toString().uppercase(Locale.getDefault())
        letterTvC.text = letterTvC.text.toString().uppercase(Locale.getDefault())
        letterTvV.text = letterTvV.text.toString().uppercase(Locale.getDefault())
        letterTvB.text = letterTvB.text.toString().uppercase(Locale.getDefault())
        letterTvN.text = letterTvN.text.toString().uppercase(Locale.getDefault())
        letterTvM.text = letterTvM.text.toString().uppercase(Locale.getDefault())
    }

    /**
     * 显示小写文本
     */
    private fun showLowerText() {
        letterTvQ.text = letterTvQ.text.toString().lowercase(Locale.getDefault())
        letterTvW.text = letterTvW.text.toString().lowercase(Locale.getDefault())
        letterTvE.text = letterTvE.text.toString().lowercase(Locale.getDefault())
        letterTvR.text = letterTvR.text.toString().lowercase(Locale.getDefault())
        letterTvT.text = letterTvT.text.toString().lowercase(Locale.getDefault())
        letterTvY.text = letterTvY.text.toString().lowercase(Locale.getDefault())
        letterTvU.text = letterTvU.text.toString().lowercase(Locale.getDefault())
        letterTvI.text = letterTvI.text.toString().lowercase(Locale.getDefault())
        letterTvO.text = letterTvO.text.toString().lowercase(Locale.getDefault())
        letterTvP.text = letterTvP.text.toString().lowercase(Locale.getDefault())
        letterTvA.text = letterTvA.text.toString().lowercase(Locale.getDefault())
        letterTvS.text = letterTvS.text.toString().lowercase(Locale.getDefault())
        letterTvD.text = letterTvD.text.toString().lowercase(Locale.getDefault())
        letterTvF.text = letterTvF.text.toString().lowercase(Locale.getDefault())
        letterTvG.text = letterTvG.text.toString().lowercase(Locale.getDefault())
        letterTvH.text = letterTvH.text.toString().lowercase(Locale.getDefault())
        letterTvJ.text = letterTvJ.text.toString().lowercase(Locale.getDefault())
        letterTvK.text = letterTvK.text.toString().lowercase(Locale.getDefault())
        letterTvL.text = letterTvL.text.toString().lowercase(Locale.getDefault())
        letterTvZ.text = letterTvZ.text.toString().lowercase(Locale.getDefault())
        letterTvX.text = letterTvX.text.toString().lowercase(Locale.getDefault())
        letterTvC.text = letterTvC.text.toString().lowercase(Locale.getDefault())
        letterTvV.text = letterTvV.text.toString().lowercase(Locale.getDefault())
        letterTvB.text = letterTvB.text.toString().lowercase(Locale.getDefault())
        letterTvN.text = letterTvN.text.toString().lowercase(Locale.getDefault())
        letterTvM.text = letterTvM.text.toString().lowercase(Locale.getDefault())
    }

    /**
     * 停止自动删除的定时器
     */
    private fun stopAutoDeleteTimer() {
        DebugUtil.warnOut(TAG, "stopAutoDeleteTimer")
        autoDeleteTimer?.shutdownNow()
        autoDeleteTimer = null
    }

    /**
     * 开启自动删除的定时器
     */
    private fun startAutoDeleteTimer() {
        stopAutoDeleteTimer()
        autoDeleteTimer = newScheduledExecutorService(1)
        autoDeleteTimer?.scheduleAtFixedRate(
            { BaseManager.handler.post { pressKey(KeyEvent.KEYCODE_DEL) } },
            0,
            100,
            TimeUnit.MILLISECONDS
        )
    }

    /**
     * 触发数字按键
     *
     * @param keycode 按键码
     */
    @Synchronized
    private fun pressKey(keycode: Int) {
        val activity = if (context is Activity) {
            context as Activity
        } else {
            return
        }
        activity.dispatchKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, keycode))
        activity.dispatchKeyEvent(KeyEvent(KeyEvent.ACTION_UP, keycode))
    }

    /**
     * 触发小写字母按键
     *
     * @param keycode 按键码
     */
    @Synchronized
    private fun pressLetterKey(keycode: Int) {
        if (!capslockCb.isChecked) {
            pressKey(keycode)
        } else {
            pressUpperLetterKey(keycode)
        }
    }

    /**
     * 触发大写字母按键
     *
     * @param keycode 按键码
     */
    private fun pressUpperLetterKey(keycode: Int) {
        @SuppressLint("HardwareIds") val keyEvent = KeyEvent(
            System.currentTimeMillis(), (keycode + 36).toChar()
                .toString(), 1, KeyEvent.FLAG_VIRTUAL_HARD_KEY
        )
        val activity = if (context is Activity) {
            context as Activity
        } else {
            return
        }
        activity.dispatchKeyEvent(keyEvent)
    }

    companion object {
        private val TAG = LetterInputMethodView::class.java.simpleName
    }
}